// internal/middleware/auth.go
package middleware

import (
	"strings"

	"github.com/gin-gonic/gin"
	"gozrd-admin-api/pkg/auth"
	"gozrd-admin-api/pkg/response"
)

// AuthMiddleware JWT认证中间件
func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取请求头中的Authorization
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			response.Fail(c, 401, "未授权")
			c.Abort()
			return
		}

		// 检查Authorization格式
		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			response.Fail(c, 401, "认证格式错误")
			c.Abort()
			return
		}

		// 解析JWT - 使用pkg/auth包
		claims, err := auth.ParseToken(parts[1])
		if err != nil {
			response.Fail(c, 401, "认证失败")
			c.Abort()
			return
		}

		// 将用户信息存入上下文
		c.Set("admin_id", claims.AdminID)
		c.Set("username", claims.Username)

		c.Next()
	}
}
